﻿using System;
using System.Data;
using System.Configuration;
using System.IO;
using System.Linq;
using System.Net;
using System.Security.Cryptography;
using System.Text;
using System.Text.RegularExpressions;
using System.Web;
using System.Web.Security;
using System.Web.UI;
using System.Web.UI.HtmlControls;
using System.Web.UI.WebControls;
using System.Web.UI.WebControls.WebParts;
using System.Xml.Linq;
using Yonkly.Models;

namespace Yonkly.Utility
{
    public class Utils
    {
        public static string GetGravatar(string email)
        {
            return GetGravatar(email, 32);
        }

        public static string GetGravatar(string email, int size)
        {
            if (string.IsNullOrEmpty(email)) return string.Empty;

            byte[] hash;

            using (MD5 md5 = MD5.Create())
            {
                byte[] data = Encoding.Default.GetBytes(email.ToLower());
                hash = md5.ComputeHash(data);
            }

            StringBuilder result = new StringBuilder();

            for (int i = 0; i < hash.Length; i++)
            {
                result.Append(hash[i].ToString("x2"));
            }

            return string.Format("http://www.gravatar.com/avatar.php?gravatar_id={0}&size={1}", result.ToString(), size);
        }

        internal static char GetRandomCharacter()
        {
            char[] pwdCharArray = "ABCDEFGHIJKLMNOPQRSTUVWXYZ0123456789".ToCharArray();
            int firstPosition = new Random().Next(pwdCharArray.GetLowerBound(0), pwdCharArray.GetUpperBound(0));
            int randomCharPosition = firstPosition;
            while (randomCharPosition == firstPosition)
            {
                randomCharPosition = new Random().Next(pwdCharArray.GetLowerBound(0), pwdCharArray.GetUpperBound(0));
            }
            char randomChar = pwdCharArray[randomCharPosition];
            return randomChar;
        }

        public static string MakeTinyUrl(string Url)
        {
            try
            {
                if (Url.Length <= 30)
                {
                    return Url;
                }
                if (!Url.ToLower().StartsWith("http") && !Url.ToLower().StartsWith("ftp"))
                {
                    Url = "http://" + Url;
                }
                var request = WebRequest.Create("http://tinyurl.com/api-create.php?url=" + Url);
                var res = request.GetResponse();
                string text;
                using (var reader = new StreamReader(res.GetResponseStream()))
                {
                    text = reader.ReadToEnd();
                }
                return text;
            }
            catch (Exception)
            {
                return Url;
            }
        }

        public static void Log(Exception ex)
        {
            try
            {
                if (ex == null)
                {
                    return;
                }

                if (ConfigurationManager.AppSettings["enableLogging"] != null
                   && Convert.ToBoolean(ConfigurationManager.AppSettings["enableLogging"]) == false)
                    return;

                using (var dc = new YonklyDataContext())
                {
                    var errorlog = new ErrorLog();
                    errorlog.Message = ex.Message;
                    if (ex.InnerException != null)
                    {
                        errorlog.Message2 = ex.InnerException.Message;
                    }
                    errorlog.StackTrace = ex.StackTrace;
                    errorlog.CreatedOn = DateTime.Now.ToUniversalTime();
                    dc.ErrorLogs.InsertOnSubmit(errorlog);
                    dc.SubmitChanges();
                }
            }
            catch
            {
                //ignore logging errors
            }
        }

        public static string ConvertMessageToHtml(string text)
        {
            if (string.IsNullOrEmpty(text))
            {
                return string.Empty;
            }
            var UsernameExpression = new Regex(@"^(@[a-zA-Z_0-9]*)|(\s@[a-zA-Z_0-9]*)|(\s@[a-zA-Z_0-9]*)$",
                                                 RegexOptions.Compiled | RegexOptions.IgnoreCase |
                                                 RegexOptions.Singleline);
            var _html = UsernameExpression.Replace(text,
                                                      match =>
                                                      string.Format("{1}@<a href='/{0}'>{0}</a>",
                                                                    match.ToString().Trim().Substring(1),
                                                                    (match.ToString().StartsWith("@") ? "" : " ")));

            var UrlExpression =
                new Regex(
                    @"((http|ftp|https):\/\/)?[\w\-_]+(\.[\w\-_]+)+([\w\-\.,@?^=%&amp;:/~\+#]*[\w\-\@?^=%&amp;/~\+#])?",
                    RegexOptions.Compiled | RegexOptions.IgnoreCase | RegexOptions.Singleline);
            _html = UrlExpression.Replace(_html, match => MakeTinyUrl(match.ToString()));

            _html = UrlExpression.Replace(_html,
                                          match =>
                                          string.Format("<a href='{0}' target='_blank'>{1}</a>",
                                                        match.ToString().ToLower().StartsWith("http") ? match.ToString() : string.Format("http://{0}", match.ToString()),
                                                        match.ToString()));

            // _html = _html.Replace("'", "\"");
            return _html;
        }

        public static void RestoreCookies(HttpContext context)
        {

            /* Fix for the Flash Player Cookie bug in Non-IE browsers.
                         * Since Flash Player always sends the IE cookies even in FireFox
                         * we have to bypass the cookies by sending the values as part of the POST or GET
                         * and overwrite the cookies with the passed in values.
                         * 
                         * The theory is that at this point (BeginRequest) the cookies have not been read by
                         * the Session and Authentication logic and if we update the cookies here we'll get our
                         * Session and Authentication restored correctly
                         */

            try
            {
                string session_param_name = "ASPSESSID";
                //string session_cookie_name = ".yonkly";
                string session_cookie_name = "ASP.NET_SessionId";

                if (HttpContext.Current.Request.Form[session_param_name] != null)
                {
                    UpdateCookie(context, session_cookie_name, HttpContext.Current.Request.Form[session_param_name]);
                }
                else if (HttpContext.Current.Request.QueryString[session_param_name] != null)
                {
                    UpdateCookie(context, session_cookie_name, HttpContext.Current.Request.QueryString[session_param_name]);
                }
            }
            catch (Exception)
            {
                //Response.StatusCode = 500;
                //Response.Write("Error Initializing Session");
            }

            try
            {
                string auth_param_name = "AUTHID";
                //string auth_param_name = ".yonkly";
                string auth_cookie_name = FormsAuthentication.FormsCookieName;

                if (HttpContext.Current.Request.Form[auth_param_name] != null)
                {
                    UpdateCookie(context, auth_cookie_name, HttpContext.Current.Request.Form[auth_param_name]);
                }
                else if (HttpContext.Current.Request.QueryString[auth_param_name] != null)
                {
                    UpdateCookie(context, auth_cookie_name, HttpContext.Current.Request.QueryString[auth_param_name]);
                }

            }
            catch (Exception)
            {
                //Response.StatusCode = 500;
                //Response.Write("Error Initializing Forms Authentication");
            }
        }

        static void UpdateCookie(HttpContext context, string cookie_name, string cookie_value)
        {
            HttpCookie cookie = context.Request.Cookies.Get(cookie_name);
            if (cookie == null)
            {
                cookie = new HttpCookie(cookie_name);
                context.Request.Cookies.Add(cookie);
            }
            cookie.Value = cookie_value;
            context.Request.Cookies.Set(cookie);
        }
    }
}
